package com.czh.service.impl;

import com.alibaba.fastjson.JSON;
import com.czh.domain.ResponseResult;
import com.czh.domain.entity.LoginUser;
import com.czh.domain.entity.User;
import com.czh.enums.AppHttpCodeEnum;
import com.czh.hander.exception.SystemException;
import com.czh.service.AdminLoginService;
import com.czh.utils.JwtUtil;
import com.czh.utils.RedisCache;
import com.czh.utils.SecurityUtils;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

@Service
public class AdminLoginServiceImpl implements AdminLoginService{
    @Resource
    private AuthenticationManager authenticationManager;

    @Resource
    private RedisCache redisCache;
    @Override
    public ResponseResult<Map<String,String>> login(User user) {
        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(user.getUserName(),user.getPassword());
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);
        if (authenticate==null){
            throw new SystemException(AppHttpCodeEnum.LOGIN_ERROR);
        }
        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
        String userId = loginUser.getUser().getId().toString();
        String userToken = JwtUtil.genAccessToken(userId);
        redisCache.setCacheObject("adminlogin"+userId,loginUser);

        Map<String,String> userData = new HashMap<>();
        userData.put("token", userToken);
        return ResponseResult.okResult(userData);
    }

    @Override
    public ResponseResult<Object> logout() {
        if (SecurityUtils.isAdmin()){
            redisCache.deleteObject("adminlogin"+SecurityUtils.getUserId());
        }
        return ResponseResult.okResult();
    }
}
